package com.qf.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


/**
 * @author Wy
 * @version V1.0
 * @Project MavenDemo
 * @Package com.qf.listener
 * @Description:
 * @Date 2022/7/4 16:57
 */
//将这个类注册到spring容器中, 作为一个javabean
@Component
public class HelloListener {
/**
 * 这是一个消息处理方法, 用来从mq服务器的队列中接收数据
 * @param str
 */
       @Autowired
       private  RedisTemplate redisTemplate;

       @RabbitListener(queues = "testquery3")
       public void messageHandler (String str, Channel channel, Message message)  throws Exception{
            //获取存入的唯一id
           String o = (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
            //往这个Key里面放值,如果能放进去就能执行下面的内容
           if(redisTemplate.opsForValue().setIfAbsent(o,"0", 3, TimeUnit.SECONDS)){
               //获取队列中的内容
               System.out.println("消费消息"+str);
                //修改value的值为1，表示已经执行成功
               redisTemplate.opsForValue().set(o,"1",3, TimeUnit.SECONDS );
               //4.手动ack，让队列删除内容
               channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
           }else{
               //5. 获取Redis中的value即可 如果是1，手动ack
               channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
               }

       }
}
